import { Button, Card, message, Table } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import enums from '../enums';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import styles from '../../../components/common/PateoTable/TableList.less';
import Ellipsis from '../../../components/Ellipsis';
import AddModal from './addModal';
import EditModal from './editModal';
import { filterAuth } from '@/support/common';
import MaskText from '@/components/MaskText';

class AnomalousEvent extends PureComponent {
  componentDidMount() {
    this.handleTableData();
  }

  handleTableData = () => {
    const { curPage, pageSize, enable } = this.state;
    this.setState({
      tableLoading: true,
    });
    this.props.dispatch({
      type: 'anomalousEvent/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/event/page',
        ...{ curPage, pageSize, enable },
      },
      callback: (response) => {
        if (response && response.statusCode == '0' && response.data) {
          if (response.data.rows.length === 0 && response.data.pagination.current > 1) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              },
            );
          } else {
            this.setState({
              tableData: response.data?.rows || [],
              total: response.data?.pagination?.total || 0,
            });
          }
          // } else {
          //   if (response.statusCode !== '0') {
          //     message.error(response.statusMessage);
          //   }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  state = {
    addModalVisible: false,
    editModalVisible: false,
    editModalData: null,
    tableData: [],
    curPage: 1,
    pageSize: 10,
    total: 0,
    tableLoading: false,
  };

  handleEdit = (record) => {
    this.setState({
      editModalVisible: true,
      editModalData: record,
    });
  };
  handleDelete = (uuid) => {
    this.props.dispatch({
      type: 'anomalousEvent/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/event/delete',
        uuid: uuid,
      },
      callback: (response) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
          // } else {
          //   message.error(response.statusMessage);
        }
      },
    });
  };
  handleEnable = (uuid) => {
    this.props.dispatch({
      type: 'anomalousEvent/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/event/enable',
        uuid: uuid,
        enable: enums.riskEventEnable.effective.value,
      },
      callback: (response) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
          // } else {
          //   message.error(response.statusMessage);
        }
      },
    });
  };
  handleDisable = (uuid) => {
    this.props.dispatch({
      type: 'anomalousEvent/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/event/enable',
        uuid: uuid,
        enable: enums.riskEventEnable.disable.value,
      },
      callback: (response) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
          // } else {
          //   message.error(response.statusMessage);
        }
      },
    });
  };
  handleAdd = () => {
    this.setState({
      addModalVisible: true,
    });
  };

  changeAddModalVisible = (flag) => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        addModalVisible: false,
      });
    } else {
      this.setState({
        addModalVisible: false,
      });
    }
  };

  changeEditModalVisible = (flag) => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    } else {
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    }
  };

  render() {
    const {
      location: { pathname = '/' },
      permissions,
    } = this.props;
    const {
      tableData,
      addModalVisible,
      editModalVisible,
      editModalData,
      total,
      tableLoading,
      curPage,
      pageSize,
    } = this.state;

    // const editBtnAuth = this.context.authButton.includes(
    //   "thirdOrgCreditVehicleAnomalousEvent-edit"
    // );
    // const deleteBtnAuth = this.context.authButton.includes(
    //   "thirdOrgCreditVehicleAnomalousEvent-delete"
    // );
    // const enableBtnAuth = this.context.authButton.includes(
    //   "thirdOrgCreditVehicleAnomalousEvent-enable"
    // );
    // const disableBtnAuth = this.context.authButton.includes(
    //   "thirdOrgCreditVehicleAnomalousEvent-disable"
    // );

    const columns = [
      {
        title: '异常事件',
        dataIndex: 'riskEventContent',
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '生效状态',
        dataIndex: 'enable',
        render: (text) => {
          let findText = enums.riskEventEnable.array.find((e) => e.value === text);
          return findText ? findText.label : text;
        },
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val) {
          return <MaskText text={val} type="name" />;
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text) => {
          if (text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss');
          }
        },
      },
      {
        title: '操作',
        dataIndex: 'uuid',
        fixed: 'right',
        render: (text, record) => {
          const btns = [];
          const editBtn = {
            title: '修改',
            key: 'edit',
            auth: 'anomalousEvent-edit',
            onConfirm: () => this.handleEdit(record),
          };
          const deleteBtn = {
            title: '删除',
            auth: 'anomalousEvent-delete',
            Popconfirm: true,
            message: '确认要删除吗?',
            key: 'delete',
            onConfirm: () => this.handleDelete(text),
          };
          const enableBtn = {
            title: '启用',
            auth: 'anomalousEvent-enable',
            Popconfirm: true,
            message: '确认要启用吗?',
            key: 'enable',
            onConfirm: () => this.handleEnable(text),
          };
          const disableBtn = {
            title: '停用',
            auth: 'anomalousEvent-disable',
            Popconfirm: true,
            message: '确认要停用吗?',
            key: 'disable',
            onConfirm: () => this.handleDisable(text),
          };

          //是否被已经生效的预警信息使用
          const isRiskWarnMsgEffective =
            record.riskWarnMsgEnable == enums.warnMsgEnable.effective.value;
          //是否被已经生效的风控规则使用
          const isRiskRuleEffective = record.riskRuleEnable == enums.riskRuleEnable.effective.value;
          // 非系统预设异常事件才有操作按钮
          if (!record.isSystem) {
            if (record.enable === enums.riskEventEnable.ineffective.value) {
              btns.push(deleteBtn);
              btns.push(enableBtn);
              btns.push(editBtn);
            }
            if (record.enable === enums.riskEventEnable.effective.value) {
              if (!isRiskWarnMsgEffective && !isRiskRuleEffective) btns.push(disableBtn);
            }
            if (record.enable === enums.riskEventEnable.disable.value) {
              btns.push(enableBtn);
              btns.push(editBtn);
            }
          }

          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];

    const pagination = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      size: 'small',
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };

    const tableProps = {
      columns,
      pagination,
      rowKey: 'uuid',
      scroll: { x: 'max-content' },
      loading: tableLoading,
      dataSource: tableData,
      onChange: (pagination) => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          },
        );
      },
    };
    return (
      <div>
        <Card bordered={false}>
          {filterAuth('anomalousEvent-add', permissions, pathname) ? (
            <div className="my_newItem">
              <Button size="small" type="primary" onClick={() => this.handleAdd()}>
                新建异常事件
              </Button>
            </div>
          ) : null}
          <Table {...tableProps} />
        </Card>
        {addModalVisible ? <AddModal changeAddModalVisible={this.changeAddModalVisible} /> : null}
        {editModalVisible ? (
          <EditModal
            editModalData={editModalData}
            changeEditModalVisible={this.changeEditModalVisible}
          />
        ) : null}
      </div>
    );
  }
}
export default connect((state) => {
  return {
    permissions: state?.menu?.permissions,
    anomalousEvent: state.anomalousEvent,
  };
})(AnomalousEvent);
